<?php
namespace wogu2\mvc\router\http;

use wogu2\mvc\router\RouterInterface;
use wogu2\stdlib\RequestInterface;

class Regex implements RouterInterface
{
    public function match(RequestInterface $request) {
        $url = $request->getParameter('url', 'get');
        if(!empty($url)) {
            $routerMap = $this->_runtime->routerMap;
            $routerConfig = $this->_runtime->routerConfig;
            foreach($routerMap as $rule => $ruleConfig) {
                if(preg_match($rule, $url, $matches)) {
                    $namespace = isset($ruleConfig['namespace']) ? $matches[$ruleConfig['namespace']] : $ruleConfig['defaultNamespace'];
                    $action = isset($ruleConfig['action']) ? $matches[$ruleConfig['action']] : $ruleConfig['defaultAction'];

                    if(!isset($this->_runtime->actionsMap[$namespace][$action])) {
                        $namespace = $routerConfig['defaultErrorNamespace'];
                        $action = $routerConfig['defaultErrorAction'];
                    }
                    
                    $this->_runtime->actionConfig = $this->_runtime->actionsMap[$namespace][$action];
                    if(isset($ruleConfig['params'])) {
                        foreach($ruleConfig['params'] as $name => $mix) {
                            if(isset($matches[$mix])) {
                                $value = $matches[$mix];
                            } elseif(isset($ruleConfig['defaultParams'][$name])) {
                                $value = $ruleConfig['defaultParams'][$name];
                            }
                            $this->_runtime->valueStack[$name] = isset($value) ? $value : null;
                        }
                    }

                    return true;
                }
            }
        }
        
        return false;
    }
}